package com.zxy.demo.guava.concurrent;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.*;

/**
 * AsyncFunctionDemo.
 * 
 * Created by zxybird on 2018/1/30.
 */
public class AsyncFunctionDemo implements AsyncFunction<Long, String> {

  private ConcurrentMap<Long, String> map = Maps.newConcurrentMap();
  {
    map.put(1L, "1L");
  }

  private Map<Long, String> service = Maps.newHashMap();

  private ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));

  @Override
  public ListenableFuture<String> apply(Long input) throws Exception {

    if (map.containsKey(input)) {

      SettableFuture listenableFuture = SettableFuture.create();
      listenableFuture.set(map.get(input));
      return listenableFuture;
    } else {
      return executorService.submit(() -> {
        // service中通过input获取retrieved
        String retrieved = service.get(input);
        map.putIfAbsent(input, retrieved);
        return retrieved;
      });
    }

  }

  public static void main(String[] args) throws Exception {
    AsyncFunctionDemo demo = new AsyncFunctionDemo();
    ListenableFuture future = demo.apply(1L);
    System.out.println(future.get());
  }
}
